package com.fanketly.funacg2.ui.screen


import android.util.Log
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.LayoutCoordinates
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import cafe.adriel.bonsai.core.Bonsai
import cafe.adriel.bonsai.core.BonsaiStyle
import cafe.adriel.bonsai.core.node.Branch
import cafe.adriel.bonsai.core.node.Leaf
import cafe.adriel.bonsai.core.tree.Tree
import cafe.adriel.bonsai.core.tree.TreeScope
import coil.compose.AsyncImage
import com.fanketly.funacg2.data.AUDIO
import com.fanketly.funacg2.data.FOLDER
import com.fanketly.funacg2.data.model.Children
import com.fanketly.funacg2.data.model.WorkList
import com.fanketly.funacg2.ui.components.*
import com.fanketly.funacg2.ui.screen.destinations.PlayListDestination
import com.fanketly.funacg2.ui.theme.FunACG2Theme
import com.fanketly.funacg2.ui.viewmodels.FavouriteViewModel
import com.fanketly.funacg2.ui.viewmodels.HomeViewModel
import com.fanketly.funacg2.ui.viewmodels.MusicViewModel
import com.fanketly.funacg2.ui.viewmodels.state.GlobalState
import com.fanketly.funacg2.utils.TimeUtils
import com.fanketly.funacg2.utils.ToastUtils
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.navigation.DestinationsNavigator

@Destination
@Composable
fun Detail(
    homeViewModel: HomeViewModel,
    musicViewModel: MusicViewModel,
    favouriteViewModel: FavouriteViewModel,
    navigator: DestinationsNavigator,
) {
    Log.i("TAG", "Detail: " + homeViewModel.globalState)
    if (homeViewModel.globalState is GlobalState.Close) {
//        navigator.navigateUp()
        return
    }
    val globalState = remember {
        Log.i("TAG", "Detail2: " + homeViewModel.globalState)
        homeViewModel.globalState as GlobalState.ToDetail
    }
    LaunchedEffect(key1 = Unit, block = {
        favouriteViewModel.checkFavourite(globalState.work.id)
    })
    BackHandler {
        navigator.navigateUp()
        homeViewModel.setStateClose()
    }
    TutorialContent(globalState.work,
        globalState.list,
        musicViewModel,
        favouriteViewModel.isFavourite,
        onFavourite = {
            if (favouriteViewModel.favouriteOrCancel(globalState.work)) {
                ToastUtils.shortToast("收藏成功")
            }
        },
        onPlayList = {
            navigator.navigate(PlayListDestination)
        },
        onBackClick = {
            navigator.navigateUp()
            homeViewModel.setStateClose()
        })
}

@OptIn(ExperimentalMaterialApi::class)
@Composable
private fun TutorialContent(
    work: WorkList.Work,
    list: ArrayList<Children>,
    musicViewModel: MusicViewModel,
    isFavourite: Boolean,
    onFavourite: () -> Unit,
    onPlayList: () -> Unit,
    onBackClick: () -> Unit,
) {
    val view = LocalView.current
    val localDensity = LocalDensity.current
    val peekHeight = remember {
        mutableStateOf(BackdropScaffoldDefaults.PeekHeight)
    }
    val backdropScaffoldState = rememberBackdropScaffoldState(initialValue = BackdropValue.Revealed)
//    var favourite by remember {
//        mutableStateOf(isFavourite)
//    }
//    val coroutineScope = rememberCoroutineScope()
    BackdropScaffold(
//        backLayerContentColor = androidx.compose.material3.MaterialTheme.colorScheme.onSurface,
        backLayerBackgroundColor = MaterialTheme.colorScheme.surface,
        frontLayerBackgroundColor = MaterialTheme.colorScheme.surfaceVariant,
//        frontLayerContentColor = androidx.compose.material3.MaterialTheme.colorScheme.onPrimary,
        frontLayerScrimColor = MaterialTheme.colorScheme.surface.copy(
            alpha = 0.60f
        ),
        //        frontLayerScrimColor = Color.Unspecified,
        appBar = {
            TopAppBar(backgroundColor = MaterialTheme.colorScheme.background,
                elevation = 8.dp,
                title = {
                    androidx.compose.material3.Text(
                        work.title,
                        overflow = TextOverflow.Ellipsis,
                        style = MaterialTheme.typography.titleSmall,
                        modifier = Modifier.wrapContentHeight(),
                    )
                },
                navigationIcon = {
                    BackIconButton(
                        onBackClick = onBackClick
//                        if (backdropScaffoldState.isRevealed) {
//                            coroutineScope.launch { backdropScaffoldState.conceal() }
//                        } else if (backdropScaffoldState.isConcealed) {
//                            coroutineScope.launch { backdropScaffoldState.reveal() }
//                        }
                    )
                },
                actions = {
                    androidx.compose.material3.IconButton(//收藏
                        modifier = Modifier, onClick = {
                            onFavourite()
                        }) {
                        androidx.compose.material3.Icon(
                            Icons.Filled.Favorite,
                            null,
                            tint = if (isFavourite) MaterialTheme.colorScheme.primary else Color.Gray
                        )
                    }
                })
        },
        scaffoldState = backdropScaffoldState,
        //背层隐藏时可见部分的高度。
        peekHeight = peekHeight.value,
        //显示后层时是否应显示应用栏。默认情况下，它将始终显示在底层内容的上方。
        // 如果设置为false ，则后台层将自动在应用栏及其内容之间切换，并带有动画。
        persistentAppBar = true,
//        backLayerBackgroundColor = MaterialTheme.colors.primary,
        backLayerContent = {
            BackLayerContent(list, onAddPlayList = {
                musicViewModel.addToPlayList(work.id, work.thumbnailCoverUrl, it)
                ToastUtils.shortToast("添加成功")
            }) { title, url ->
                musicViewModel.playAudioByInfo(
                    work.id,
                    title,
                    url,
                    work.thumbnailCoverUrl
                )
            }
        },
        stickyFrontLayer = true, //前层是否贴到后层的高度
        headerHeight = BackdropScaffoldDefaults.HeaderHeight,
        frontLayerShape = BackdropScaffoldDefaults.frontLayerShape,
        frontLayerElevation = BackdropScaffoldDefaults.FrontLayerElevation,
        frontLayerContent = {
            FrontLayerContent(
                musicViewModel = musicViewModel, onFavourite = onFavourite, onPlayList = onPlayList
            ) {
                //计算底部音乐播放组件占用的高度
                peekHeight.value =
                    with(localDensity) { (view.height - it.size.height).toDp() - 8.dp }

            }
        }) {

    }
}

@Composable
private fun BackLayerContent(
    list: ArrayList<Children>,
    onAddPlayList: (list: List<Children>) -> Unit,
    onPlay: (title: String, url: String) -> Unit,
) {

    val tree = Tree<Children> {
        //循环判断是不是目录
        list.forEach {
            FolderItem(it = it)
        }
    }
    Bonsai(tree = tree, modifier = Modifier.fillMaxHeight(), style = BonsaiStyle<Children>().copy(
        toggleIconSize = 30.dp,
        toggleIconColorFilter = ColorFilter.tint(MaterialTheme.colorScheme.onSurface),
        nodeNameTextStyle = TextStyle(
            fontWeight = FontWeight.Medium,
            fontSize = 20.sp,
            color = MaterialTheme.colorScheme.onSurface
        )
    ), onClick = {
        val content = it.content
        if (content.type == FOLDER) {
            tree.clearSelection()
            tree.toggleExpansion(it)
        } else if (content.type == AUDIO) {
            onPlay(content.title, content.mediaStreamUrl!!)
        }
    }, onDoubleClick = {
        val content = it.content
        if (content.type == FOLDER) {
            val filter = content.children?.filter { a -> a.type == AUDIO }
            if (filter != null) onAddPlayList(filter)
        }
    })
}

@Composable
private fun TreeScope.FolderItem(
    it: Children,
) {
    if (it.type == FOLDER) {
        Branch(content = it, name = it.title) {
            it.children!!.forEach { a ->
                FolderItem(it = a)
            }
        }
    } else if (it.type == AUDIO) {
        Leaf(content = it, name = it.title)
    }
}

/**
 * @param onGloballyPositioned  可以提供当前组件的大小
 * */
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun FrontLayerContent(
    musicViewModel: MusicViewModel,
    onFavourite: () -> Unit,
    onPlayList: () -> Unit,
    onGloballyPositioned: (LayoutCoordinates) -> Unit,
) {
    // TODO: 将来要移出这里
    var openDialog by remember {
        mutableStateOf(false)
    }
    if (openDialog) TimerDialog(musicViewModel.getStopRemainingTime(), onDismiss = {
        openDialog = false
    }, onConfirm = {
        musicViewModel.setStopTimer(it)
        openDialog = false
    }) {
        openDialog = false
    }
    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier.onGloballyPositioned(onGloballyPositioned)
    ) {
        CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
            androidx.compose.material3.Text(
                text = musicViewModel.audioInfo.songName,
                modifier = Modifier.padding(top = 16.dp, start = 8.dp, end = 8.dp, bottom = 8.dp)
            )
        }
        androidx.compose.material3.Divider(
            modifier = Modifier
                .padding(horizontal = 8.dp)
                .height(1.dp), color = Color.LightGray
        )
        Spacer(modifier = Modifier.height(8.dp))
        if (musicViewModel.audioInfo.songCover.isNotEmpty()) androidx.compose.material3.Surface(
            shape = MaterialTheme.shapes.large
        ) {
            AsyncImage(
                model = musicViewModel.audioInfo.songCover,
                contentDescription = null,
//                placeholder = painterResource(id = R.drawable.ic_not_photo),
//                error = painterResource(id = R.drawable.ic_not_photo),
                modifier = Modifier
                    .fillMaxWidth(0.8f)
                    .heightIn(100.dp, 400.dp),
                contentScale = ContentScale.FillWidth
            )
        }
        // TODO: 收藏和定时的点击事件需要向外抛出
        ProgressBarWithTwoIcon(musicViewModel = musicViewModel,
            modifier = Modifier.padding(top = 12.dp),
            onFavourite = onFavourite,
            onTimer = {
                openDialog = true
            })
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier
                .padding(top = 12.dp)
                .fillMaxWidth(1f)
                .wrapContentHeight()
        ) {
            //播放模式
            PlayModelIconButton(
                mode = musicViewModel.audioRepeatMode,
                Modifier.weight(1f),
                onClick = musicViewModel::changeRepeatMode
            )
            androidx.compose.material3.Icon(
                imageVector = Icons.Filled.Replay10,
                modifier = Modifier
                    .weight(1f)
                    .combinedClickable(
                        indication = rememberRipple(
                            bounded = false, radius = 20.dp
                        ),
                        interactionSource = remember { MutableInteractionSource() },
                        role = Role.Button,
                        onClick = musicViewModel::replay10,
                        onDoubleClick = musicViewModel::previous//双击上一首
                    ),
                contentDescription = null,
                tint = MaterialTheme.colorScheme.primary
            )
//            }
            //暂停或重新播放
            PlayOrPauseIconButton(
                musicViewModel.isPlaying,
                Modifier.weight(1f),
                onClick = musicViewModel::pauseOrRestoreMusic
            )
            androidx.compose.material3.Icon(
                imageVector = Icons.Filled.Forward30,
                modifier = Modifier
                    .weight(1f)
                    .combinedClickable(
                        indication = rememberRipple(
                            bounded = false, radius = 20.dp
                        ),
                        interactionSource = remember { MutableInteractionSource() },
                        role = Role.Button,
                        onClick = musicViewModel::forward30,
                        onDoubleClick = musicViewModel::next//双击下一首
                    ),
                contentDescription = null,
                tint = MaterialTheme.colorScheme.primary
            )
//            }
            PlayListIconButton(//播放列表
                modifier = Modifier.weight(1f), toPlayList = onPlayList
            )
        }
    }
}

@Composable
fun ProgressBarWithTime(
    musicViewModel: MusicViewModel,
) {
    val allTime = musicViewModel.audioAllTime
    if (allTime == 0) return
    val nowTime = musicViewModel.audioProcess

    BoxWithConstraints(modifier = Modifier.fillMaxWidth(0.7f)) {
        // TODO: 优化
        val constraintsW = constraints.maxWidth
//        Log.i(TAG, "ProgressBarWithTime:${LocalView.current.width},$constraintsW,${constraints.minWidth} ")
        Column(
//            modifier = Modifier.fillMaxWidth(0.7f),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            AudioProgressBarTime(
                TimeUtils.timeConversion(nowTime),
                TimeUtils.timeConversion(allTime),
                modifier = Modifier.fillMaxWidth(0.96f)
            )
            AudioProgressBar(nowTime.toFloat() / allTime, onPress = {
                musicViewModel.seekToFromPercentage(it.x / constraintsW)
            }, onDragStarted = {
                musicViewModel.pause()
            }, onDragStopped = {
                musicViewModel.seekTo(nowTime)
                musicViewModel.restore()
            }) {
                Log.i("TAG", "ProgressBarWithTime: $it ,${it / constraintsW}")
                musicViewModel.onlySeekProgress(it / constraintsW)
            }
        }
    }
}

@Composable
fun ProgressBarWithTwoIcon(
    musicViewModel: MusicViewModel,
    modifier: Modifier = Modifier,
    onFavourite: () -> Unit,
    onTimer: () -> Unit,
) {
    Row(
        modifier = modifier,
        horizontalArrangement = Arrangement.Center,
        verticalAlignment = Alignment.CenterVertically
    ) {
        androidx.compose.material3.IconButton(//收藏
            modifier = Modifier.weight(1f), onClick = onFavourite
        ) {
            ControllerIcon(
                imageVector = Icons.Filled.Favorite,
                modifier = Modifier
                    .padding(top = 6.dp)
                    .fillMaxSize(0.7f),
                tint = Color.Gray
            )
        }
        ProgressBarWithTime(musicViewModel)
        androidx.compose.material3.IconButton(//定时
            modifier = Modifier.weight(1f), onClick = onTimer
        ) {
            ControllerIcon(
                imageVector = Icons.Filled.Snooze,
                modifier = Modifier
                    .padding(top = 6.dp)
                    .fillMaxSize(0.7f),
                tint = Color.Gray
            )
        }
    }
}


@Preview(showBackground = true)
@Composable
private fun Preview() {
//    AudioDetail()
    FunACG2Theme {
        Row(Modifier.fillMaxSize()) {
            PlayModelIconButton(100, onClick = {})
            androidx.compose.material3.Text(text = "aaaaa111")
            PlayModelIconButton(100, onClick = {})
        }
//        TutorialContent(
//        FrontLayerContent(
//            WorkList.Work(
//                WorkList.Work.Circle(1, ""),
//                1,
//                "",
//                1,
//                true,
//                1,
//                "",
//                "1",
//                true,
//                1,
//                emptyList(),
//                1.0,
//                1,
//                emptyList(),
//                "",
//                1,
//                "",
//                tags = emptyList(),
//                "",
//                "1",
//                userRating = 4,
//                listOf(WorkList.Work.Va("1", "233"))
//            ), AudioList2(), { _, _ -> }, {})
    }
}

